package com.lwh.videopicplayer;

import static android.view.View.GONE;
import static android.view.View.inflate;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import android.net.Network;
import android.net.wifi.WifiManager;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.LinkAddress;

import java.net.InetAddress;
import java.net.Inet4Address;

import android.net.NetworkInfo;
import android.net.TrafficStats;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.hardbacknutter.sshd.SshdService;
import com.hardbacknutter.sshd.SshdSettings;
import com.lwh.videopicplayer.utils.Utils;
import com.lwh.videopicplayer.view.PicandVideo;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class PlayActivity extends Activity {

    static final String LOG_TAG = "PlayActivity";

    Context mContext;

    static final int PLAY_STATUS_VIDEO = 1;
    static final int PLAY_STATUS_PICTURE = 2;
    static final int PLAY_STATUS_NONE = 3;

    PicandVideo player;
    int playStatus = PLAY_STATUS_NONE;

    Thread thread;
    File curadfile;
    File adfast;
    float progress;
    int minus;
    int copycount = 0;
    int count = 0;
    int copysuccess;
    int copyfaile;
    int i = 0;
    boolean isbreak;
    String mp3test = "sdcard/ad/test.mp3";
    String imgtest = "sdcard/ad/test.jpg";
    String videotest = "sdcard/ad/test.mp4";
    File curSDPath;
    int curIndex = 0;
    private TextView tvProgpress;

    private TextView mTipsText;
    private TextView mSpeedText;

    private TextView load;
    private RelativeLayout pro;
    private LinearLayout cp;

    public static Boolean isRuning = false;

    LinearLayout mLayoutRoot;
    int mRotation;
    int mScreenWidth;
    int mScreenHeight;

    private FTPClient ftpClient = null;
    private FtpThread ftpThread = null;

    // 8 floor server 192.178.5.251
    // weihai "192.178.5.203"

    private String FTP_HOSTNAME = "192.178.5.251";
    private int FTP_PORT = 21;
    private String FTP_USERNAME = "tv";
    //private String FTP_USERNAME = "adyy";
    private String FTP_PASSWORD = "Xy525300!";

    private int autoPlayTime = 30;

    FTPFile[] serverFileList = null;
    FTPFile[] serverConfList = null;

    List<FTPFile> downloadFileList = null;
    List<File> deleteFileList = null;
    File[] localFileList = null;
    int downloadedFileSum = 0;


    FTPFile[] serverBranchFileList = null;
    List<FTPFile> downloadBranchFileList = null;
    List<File> deleteBranchFileList = null;
    File[] localBranchFileList = null;
    int downloadedBranchFileSum = 0;

    List<File> localShowFileList = null;

    private String downloadFilePath = "";
    private String downloadBranchFilePath = "";

    private int ftpStatus = -1;
    private final static int FTP_INIT_OK = 0;
    private final static int FTP_INIT_FAIL = 1;
    private final static int FTP_GET_LIST_OK = 2;
    private final static int FTP_GET_LIST_FAIL = 3;
    private final static int FTP_GET_FILE = 4;
    private final static int FTP_GET_FILE_OK = 5;
    private final static int START_FTP_SYNC = 6;
    private final static int REFLASH_FILESIZE = 7;
    private final static int SHOW_NETWORK_SPEED = 8;
    public final static int PLAY_NEXT_FILE = 10;

    private MainHandler mainHandler = new MainHandler();

    boolean canUserRoll = false;

    long startRxBytes = 0;

    long downloadTotalSize = 0;
    long currentDownloadSize = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isRuning = true;

        Point localPoint = getZB(this);
        mScreenWidth = localPoint.x;
        mScreenHeight = localPoint.y;

        String value = Utils.getSystemProperty("persist.user_rotation", "0");
        if (value.equals("0"))
            mRotation = 0;
        if (value.equals("1"))
            mRotation = 90;
        if (value.equals("2"))
            mRotation = 180;
        if (value.equals("3"))
            mRotation = 270;

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_play);
        initView();

        mainHandler.sendEmptyMessageDelayed(START_FTP_SYNC, 5 * 1000);

    }

    public Point getZB(Context context) {
        Display localDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();

        localDisplay.getRealMetrics(localDisplayMetrics);
        int i = localDisplayMetrics.widthPixels;
        int j = localDisplayMetrics.heightPixels;
        Point localPoint = new Point();
        localPoint.set(i, j);
        return localPoint;
    }

    @Override
    protected void onStart() {
        super.onStart();
        setRotation();

    }

    public void setRotation() {
        LinearLayout.LayoutParams localLayoutParams = new LinearLayout.LayoutParams(-1, -1);
        localLayoutParams.gravity = Gravity.CENTER;

        if (mRotation == 0) {
            localLayoutParams.width = mScreenWidth;
            localLayoutParams.height = mScreenHeight;
            mLayoutRoot.setTranslationY(0);
            mLayoutRoot.setTranslationX(0);
            mLayoutRoot.setRotation(0.0f);

        } else if (mRotation == 90) {
            localLayoutParams.width = mScreenHeight;
            localLayoutParams.height = mScreenWidth;
            mLayoutRoot.setTranslationY((mScreenHeight - mScreenWidth) / 2);
            mLayoutRoot.setTranslationX(0);
            mLayoutRoot.setRotation(90.0F);

        } else if (mRotation == 180) {
            localLayoutParams.width = mScreenWidth;
            localLayoutParams.height = mScreenHeight;
            mLayoutRoot.setTranslationY(0);
            mLayoutRoot.setTranslationX(0);
            mLayoutRoot.setRotation(180.0F);

        } else if (mRotation == 270) {
            localLayoutParams.width = mScreenHeight;
            localLayoutParams.height = mScreenWidth;
            mLayoutRoot.setTranslationY((mScreenHeight - mScreenWidth) / 2);
            mLayoutRoot.setTranslationX(0);
            mLayoutRoot.setRotation(270.0F);

        } else {
            localLayoutParams.width = mScreenWidth;
            localLayoutParams.height = mScreenHeight;
            mLayoutRoot.setTranslationY(0);
            mLayoutRoot.setTranslationX(0);
            mLayoutRoot.setRotation(0.0f);

        }
        mLayoutRoot.setLayoutParams(localLayoutParams);
    }


    @Override
    protected void onStop() {
        super.onStop();
        player.stopPlay();
        System.exit(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i(LOG_TAG, "onKeyDown==" + keyCode);
        if (keyCode == 23) {
            showMode();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            mainHandler.removeMessages(PLAY_NEXT_FILE);
            playSource();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            mainHandler.removeMessages(PLAY_NEXT_FILE);
            curIndex = curIndex - 2;

            if (curIndex < 0) {
                curIndex = 0;
            }

            playSource();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void showMode() {


        AlertDialog dialog = new AlertDialog.Builder(this).create();//创建对话框

        dialog.setIcon(R.mipmap.ic_launcher);//设置对话框icon

        dialog.setTitle("MAC");//设置对话框标题
        //dialog.setMessage("当前机器MAC为"+Tools.getMac());

        //分别设置三个button
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();//关闭对话框

            }
        });

        dialog.show();
    }

    private void initView() {
        mContext = this;
        mLayoutRoot = (LinearLayout) findViewById(R.id.root);
        player = (PicandVideo) findViewById(R.id.pv);
        mTipsText = (TextView) findViewById(R.id.tv_tips);
        mSpeedText = (TextView) findViewById(R.id.tv_speed);
        player.setMainHandler(mainHandler);
        player.setPlayInterface(new PicandVideo.PlayInterface() {

            @Override
            public void onCompletion() {
                Log.i(LOG_TAG, "onCompletion");
                playSource();
            }

            @Override
            public void onError(MediaPlayer mp, int what, int extra) {
                Log.i(LOG_TAG, "onError==" + what);
                playSource();
            }

            @Override
            public void onPathError(Exception e) {
                Log.i(LOG_TAG, "onPathError==" + e);
                playSource();
            }
        });

        initSource();

    }

    public boolean isMediaFile(File file) {
        String name = file.getName().toLowerCase();

        return name.endsWith("mp4") || name.endsWith("mkv") ||
                name.endsWith("jpg") || name.endsWith("png");
    }

    private void initSource() {
        localShowFileList = new ArrayList<File>();

        initLocalFileList();
        initLocalBranchFileList();

        if (localFileList.length > 0 || localBranchFileList.length > 0) {
            for (File file : localFileList) {
                if (file.isFile() && isMediaFile(file)) {
                    localShowFileList.add(new File(file.getAbsolutePath()));
                }
            }

            for (File file : localBranchFileList) {
                if (file.isFile() && isMediaFile(file)) {
                    localShowFileList.add(new File(file.getAbsolutePath()));
                }
            }
        } else {

        }

        for (File file : localShowFileList) {
            if (file.isFile()) {
                Log.i(LOG_TAG, "need play file " + file.toString());
            }
        }


        if (localShowFileList.size() == 0) {
            //Toast.makeText(this, "当前没有可播放资源", Toast.LENGTH_LONG).show();
            return;
        }
        curIndex = 0;
        playSource();
    }

    @Override
    public void onBackPressed() {
        Log.d(LOG_TAG, "onBackPressed!");
        showConfirmPsdDialog();
    }

    public static String getWifiIpAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        if (!wifiManager.isWifiEnabled()) {
            // Wi-Fi is not enabled, return null or handle the case accordingly
            return null;
        }

        int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
        byte[] bytes = new byte[4];
        for (int i = 0; i < 4; ++i) {
            bytes[i] = (byte) (ipAddress >> ((3 - i) * 8));
        }

        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append((b & 0xFF)).append(".");
        }
        sb.deleteCharAt(sb.length() - 1);

        return sb.toString();
    }

    //获取有线网的ip地址
    public static String getEthernetIpAddress(Context context) {
        final Network network = getFirstEthernet(context);
        if (network == null) {
            return "";
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
        if (linkProperties != null) {
            for (LinkAddress linkAddress : linkProperties.getLinkAddresses()) {
                InetAddress inetAddress = linkAddress.getAddress();
                if (inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }
        return "";
    }

    private static Network getFirstEthernet(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final Network[] networks = connectivityManager.getAllNetworks();
        for (final Network network : networks) {
            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
            //关键：判断网络类型 有线网
            if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                return network;
            }
        }
        return null;
    }

    private void showConfirmPsdDialog() {
        Log.d(LOG_TAG, "showConfirmPsdDialog!");
        //需要自己去定义对话框的显示样式，所以要调用dialog.setView(view);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        final AlertDialog dialog = builder.create();
        final View view = inflate(mContext, R.layout.dialog_confirm_pwd, null);
        //让对话框显示一个自己定义的对话框界面效果
        dialog.setView(view);
        dialog.show();

        TextView tx_wifi = (TextView) view.findViewById(R.id.text_wifi);
        TextView tx_eth = (TextView) view.findViewById(R.id.text_eth);
        tx_wifi.setText(getWifiIpAddress(mContext));
        tx_eth.setText(getEthernetIpAddress(mContext));

        Button bt_submit = (Button) view.findViewById(R.id.bt_submit);
        Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel);
        EditText et_confirm_psd = (EditText) view.findViewById(R.id.et_confirm_psd);
        et_confirm_psd.requestFocus();
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et_confirm_psd = (EditText) view.findViewById(R.id.et_confirm_psd);
                String confirmPsd = et_confirm_psd.getText().toString();
                String psd = String.valueOf("525300");
                Log.v("PSD", confirmPsd);
                if (!confirmPsd.isEmpty()) {
                    if (psd.equals(confirmPsd)) {
                        finish();
                        dialog.dismiss();
                    } else {
                        Toast.makeText(mContext, "密码错误，请联系管理员！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //提示用户密码输入为空的情况
                    Toast.makeText(mContext, "密码输入为空！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }


    private void playSource() {
        Log.i(LOG_TAG, "playSource localShowFileList size=" + localShowFileList.size());
        if (localShowFileList.size() == 0) {
            //没有可播
            return;
        }

        //.setVisibility(GONE);
        mTipsText.setVisibility(GONE);

        Log.i(LOG_TAG, "curIndex==" + curIndex);

        if (curIndex >= localShowFileList.size()) {
            curIndex = 0;
        }

        Log.i(LOG_TAG, "curIndex==" + curIndex);

        String path = localShowFileList.get(curIndex).getAbsolutePath();
        Log.i(LOG_TAG, "path==" + path);
        File file = new File(path);
        if (file.exists()) {
            //播放视频
            Log.i(LOG_TAG, "play video path=" + path);
            player.playMediaFile(path);
            playStatus = PLAY_STATUS_VIDEO;
        }
        curIndex++;
    }


    public static int getAutoPlayTime(Context mContext) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE);
        int time = mSharedPreferences.getInt("auto_play_time", 5);
        return time;
    }

    public static void setAutoPlayTime(Context mContext, int time) {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE);
        mSharedPreferences.edit().putInt("auto_play_time", time).commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.stopPlay();
    }

    public int getUnit(float totalSizeOfFilesInDir) {
        int i = 0;
        if (totalSizeOfFilesInDir > Integer.MAX_VALUE) {
            totalSizeOfFilesInDir /= 1024;
            i++;
            //mb
            if (totalSizeOfFilesInDir > Integer.MAX_VALUE) {
                i++;
            }
        }
        return i;
    }

    public void runFtpThread() {

        try {
            SshdSettings.writePasswordFile(this, "tv", true, "Xy525300!");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Log.d(LOG_TAG, "start SshdService services!");

        if (SshdService.isRunning() != true) {
            Intent intent = new Intent(mContext, SshdService.class);
            startService(intent);
        }

        if (ftpThread != null) {
            ftpThread.interrupt();
            ftpThread = null;
        }

        ftpThread = new FtpThread();
        ftpThread.start();
    }


    public String getCurrentBranch() {
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE);
        String branch = mSharedPreferences.getString("persist.sys.branch", "");
        return branch;
    }

    public class MainHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START_FTP_SYNC:
                    Log.d(LOG_TAG, "is time to start ftp check new version!");
                    ftpStatus = -1;
                    runFtpThread();
                    mainHandler.sendEmptyMessageDelayed(START_FTP_SYNC, 10 * 60 * 1000);
                    break;
                case FTP_INIT_OK:
                    Log.d(LOG_TAG, "init ftp ok!");
                    runFtpThread();
                    break;
                case FTP_INIT_FAIL:
                    Log.d(LOG_TAG, "ftp server connect fail!");
                    mSpeedText.setText("服务器连接失败！");
                    Toast.makeText(mContext, "服务器连接失败！", Toast.LENGTH_SHORT).show();
                    break;
                case FTP_GET_LIST_OK:
                    runFtpThread();
                    break;
                case FTP_GET_LIST_FAIL:
                    Log.d(LOG_TAG, "get ftp server file list fail!");
                    Toast.makeText(mContext, "获取文件列表失败！", Toast.LENGTH_SHORT).show();

                    int time = getAutoPlayTime(mContext) * 1000;
                    if (time > 0) {
                        //mXBanner.setAutoPlayTime(time);
                    }

                    break;
                case FTP_GET_FILE:
                    runFtpThread();
                    startRxBytes = TrafficStats.getTotalRxBytes();
                    mainHandler.sendEmptyMessageDelayed(SHOW_NETWORK_SPEED, 2000);
                    break;
                case SHOW_NETWORK_SPEED:
                    long endRxBytes = TrafficStats.getTotalRxBytes();
                    double downloadSpeed = (endRxBytes - startRxBytes) / 1024.0 / 2;

                    Log.d(LOG_TAG, "currentDownloadSize " + currentDownloadSize + " downloadTotalSize " +downloadTotalSize);
                    //if (localShowFileList == null || localShowFileList.isEmpty()) {
                        mSpeedText.setText( "正在下载" + String.format("%.2f", (currentDownloadSize* 100.0 / downloadTotalSize)) + "% 速度:" + String.format("%.2f", downloadSpeed) + "KByte/s");

                        startRxBytes = endRxBytes;
                        mainHandler.sendEmptyMessageDelayed(SHOW_NETWORK_SPEED, 2000);
                    //}

                    break;
                case FTP_GET_FILE_OK:

                    Log.d(LOG_TAG, "download ok and start to auto play!");

                    mainHandler.removeMessages(SHOW_NETWORK_SPEED);
                    mSpeedText.setText("");
                    initView();

                    break;
                case PLAY_NEXT_FILE:
                    Log.d(LOG_TAG, "play next file!");
                    playSource();
                    break;
                case REFLASH_FILESIZE:
                    Log.d(LOG_TAG, "reflash file!");

                    if (localShowFileList == null || localShowFileList.isEmpty()) {
                        mTipsText.setText("正在加载资源" + (downloadedBranchFileSum + downloadedFileSum) + "/" + (downloadFileList.size() + downloadBranchFileList.size()) + "，请稍后！");
                    }
                    break;
            }
        }
    }


    class FtpThread extends Thread {


        @Override
        public void run() {

            if (ftpStatus == -1) {

                Log.d(LOG_TAG, "start connect ftp server!");
                try {
                    ftpClient = new FTPClient();

                    ftpClient.connect(FTP_HOSTNAME, FTP_PORT);
                    ftpClient.setConnectTimeout(20 * 1000);
                    ftpClient.setDataTimeout(20 * 1000);
                    // 登录FTP服务器
                    boolean login = ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
                    if (login) {
                        // 登录成功
                        Log.d(LOG_TAG, "ftp server connect ok!");
                        ftpStatus = FTP_INIT_OK;
                        mainHandler.sendEmptyMessage(FTP_INIT_OK);
                    } else {
                        // 登录失败
                        Log.d(LOG_TAG, "ftp server connect fail!");
                        ftpStatus = FTP_INIT_FAIL;
                        mainHandler.sendEmptyMessage(FTP_INIT_FAIL);
                    }
                } catch (IOException e) {
                    ftpStatus = FTP_INIT_FAIL;
                    mainHandler.sendEmptyMessage(FTP_INIT_FAIL);
                    e.printStackTrace();

                }
            } else if (ftpStatus == FTP_INIT_OK) {
                try {
                    // 设置FTP文件传输模式为被动模式
                    ftpClient.enterLocalPassiveMode();
                    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    ftpClient.setControlEncoding("UTF-8");

                    //获取文件列表
                    ftpClient.changeToParentDirectory();

                    // 获取FTP服务器上的广告切换时间配置
                    serverConfList = ftpClient.listFiles("conf/");

                    if (serverConfList != null && serverConfList.length > 0) {
                        for (FTPFile file : serverConfList) {
                            Log.d(LOG_TAG, "serverConfList=" + file.getName());
                            if (file.getName().startsWith("time_")) {
                                String timeStr = StringUtils.substringBetween(file.getName(), "time_", ".txt");
                                Log.d(LOG_TAG, "timeStr=" + timeStr);
                                int time = Integer.parseInt(timeStr);
                                Log.d(LOG_TAG, "get time=" + time);

                                if (time > 0)
                                    setAutoPlayTime(mContext, time);

                            }
                        }
                    }

                    serverFileList = ftpClient.listFiles();
                    Log.d(LOG_TAG, "sever get files size = " + serverFileList.length);

                    for (FTPFile file : serverFileList) {
                        Log.d(LOG_TAG, "fileName=" + file.getName() + " isFile=" + file.isFile() + " size=" + file.getSize());
                    }

                    serverBranchFileList = ftpClient.listFiles(new String(getCurrentBranch().getBytes("UTF-8"), "ISO-8859-1") + "/");
                    Log.d(LOG_TAG, "sever get branch files size = " + serverBranchFileList.length);

                    for (FTPFile file : serverBranchFileList) {
                        Log.d(LOG_TAG, "fileName=" + file.getName() + " isFile=" + file.isFile() + " size=" + file.getSize());
                    }

                    ftpStatus = FTP_GET_LIST_OK;
                    mainHandler.sendEmptyMessage(FTP_GET_LIST_OK);
                } catch (IOException e) {
                    mainHandler.sendEmptyMessage(FTP_GET_LIST_FAIL);
                    e.printStackTrace();

                    try {
                        ftpClient.disconnect();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            } else if (ftpStatus == FTP_GET_LIST_OK) {
                for (FTPFile file : serverFileList) {
                    // 处理每个文件
                    Log.d(LOG_TAG, "file=" + file.getName());
                }

                downloadTotalSize = 0;
                currentDownloadSize = 0;

                checkDownloadDelFile();
                checkDownloadDelBranchFile();

                if ((downloadFileList != null && deleteFileList != null) && downloadFileList.size() > 0 || deleteFileList.size() > 0 ||
                        (downloadBranchFileList != null && deleteBranchFileList != null) && downloadBranchFileList.size() > 0 || deleteBranchFileList.size() > 0) {
                    canUserRoll = false;
                    ftpStatus = FTP_GET_FILE;
                    mainHandler.sendEmptyMessage(FTP_GET_FILE);
                    Log.d(LOG_TAG, "need to download or delete file!");
                } else {
                    Log.d(LOG_TAG, "no need to download or delete file!");

                    try {
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            } else if (ftpStatus == FTP_GET_FILE) {
                Log.d(LOG_TAG, "download or delete file!");

                downloadAndDelFile();
                downloadAndDelBranchFile();

                Log.d(LOG_TAG, "download or delete end!");

                ftpStatus = FTP_GET_FILE_OK;

                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                mainHandler.sendEmptyMessage(FTP_GET_FILE_OK);
            } else {

            }
        }
    }

    public static boolean compereByteArray(byte[] b1, byte[] b2) {

        if (b1.length == 0 || b2.length == 0) {
            return false;
        }

        if (b1.length != b2.length) {
            return false;
        }

        boolean isEqual = true;

        for (int i = 0; i < b1.length && i < b2.length; i++) {
            if (b1[i] != b2[i]) {
                isEqual = false;
                break;
            }
        }
        return isEqual;
    }


    public void initLocalFileList() {
        File externalFile = mContext.getExternalFilesDir(null);
        downloadFilePath = externalFile.getAbsolutePath();
        if (externalFile != null && externalFile.listFiles() != null)
            localFileList = externalFile.listFiles();
        else
            localFileList = null;
    }

    public void initLocalBranchFileList() {
        File externalFile = mContext.getExternalFilesDir(null);
        downloadBranchFilePath = externalFile.getAbsolutePath() + "/" + getCurrentBranch();

        File externalBranchFile = new File(mContext.getExternalFilesDir(null) + "/" + getCurrentBranch());

        if (externalBranchFile != null && externalBranchFile.listFiles() != null)
            localBranchFileList = externalBranchFile.listFiles();
        else {
            externalBranchFile.mkdir();
            localBranchFileList = new File[0];
        }
    }

    public void checkDownloadDelFile() {

        deleteFileList = new ArrayList<File>();
        downloadFileList = new ArrayList<FTPFile>();

        for (File lfile : localFileList) {
            // 处理每个文件
            //Log.d(LOG_TAG, "lfile=" + lfile.getName());
            FTPFile tmpfile = null;
            boolean foundFile = false;

            if (!lfile.isFile()) {
                continue;
            }

            for (FTPFile sfile : serverFileList) {
                tmpfile = sfile;
                //Log.d(LOG_TAG, "sfile=" + sfile.getName());

                if (!sfile.isFile())
                    continue;

                try {
                    if (compereByteArray(sfile.getName().getBytes("UTF-8"), lfile.getName().getBytes("UTF-8")) && lfile.length() == sfile.getSize()) {
                        foundFile = true;
                        break;
                    } else {
                        foundFile = false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            if (!foundFile) {
                Log.d(LOG_TAG, "need to delete file =" + lfile.getName());
                deleteFileList.add(lfile);
            }
        }

        for (FTPFile sfile : serverFileList) {
            // 处理每个文件
            //Log.d(LOG_TAG, "lfile=" + sfile.getName());
            boolean foundFile = false;

            if (!sfile.isFile()) {
                continue;
            }

            for (File lfile : localFileList) {
                // 处理每个文件
                //Log.d(LOG_TAG, "sfile=" + sfile.getName());

                try {
                    if (compereByteArray(sfile.getName().getBytes("UTF-8"), lfile.getName().getBytes("UTF-8")) && lfile.length() == sfile.getSize()) {
                        foundFile = true;
                        break;
                    } else {
                        foundFile = false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (!foundFile) {
                Log.d(LOG_TAG, "need to download file =" + sfile.getName());
                downloadTotalSize += sfile.getSize();
                downloadFileList.add(sfile);
            }
        }
    }

    public void checkDownloadDelBranchFile() {

        deleteBranchFileList = new ArrayList<File>();
        downloadBranchFileList = new ArrayList<FTPFile>();

        for (File lfile : localBranchFileList) {
            // 处理每个文件
            //Log.d(LOG_TAG, "lfile=" + lfile.getName());
            FTPFile tmpfile = null;
            boolean foundFile = false;

            if (!lfile.isFile()) {
                continue;
            }

            for (FTPFile sfile : serverBranchFileList) {
                tmpfile = sfile;
                //Log.d(LOG_TAG, "sfile=" + sfile.getName());

                if (!sfile.isFile())
                    continue;

                try {
                    if (compereByteArray(sfile.getName().getBytes("UTF-8"), lfile.getName().getBytes("UTF-8")) && lfile.length() == sfile.getSize()) {
                        foundFile = true;
                        break;
                    } else {
                        foundFile = false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            if (!foundFile) {
                Log.d(LOG_TAG, "need to delete branch file =" + lfile.getName());
                deleteBranchFileList.add(lfile);
            }
        }

        for (FTPFile sfile : serverBranchFileList) {
            // 处理每个文件
            //Log.d(LOG_TAG, "lfile=" + sfile.getName());
            boolean foundFile = false;

            if (!sfile.isFile()) {
                continue;
            }

            for (File lfile : localBranchFileList) {
                // 处理每个文件
                //Log.d(LOG_TAG, "sfile=" + sfile.getName());

                try {
                    if (compereByteArray(sfile.getName().getBytes("UTF-8"), lfile.getName().getBytes("UTF-8")) && lfile.length() == sfile.getSize()) {
                        foundFile = true;
                        break;
                    } else {
                        foundFile = false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (!foundFile) {
                Log.d(LOG_TAG, "need to download branch file =" + sfile.getName());
                downloadTotalSize += sfile.getSize();
                downloadBranchFileList.add(sfile);
            }
        }


    }

    public void downloadAndDelFile() {

        downloadedFileSum = 0;

        for (File lfile : deleteFileList) {
            Log.d(LOG_TAG, "del local file=" + lfile.getName());
            if (lfile.exists())
                lfile.delete();
        }

        try {
            ftpClient.changeToParentDirectory();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (FTPFile sfile : downloadFileList) {

            try {
                String fileName = sfile.getName();
                String fileNameUTF8 = new String(fileName.getBytes("UTF-8"), "UTF-8");
                Log.d(LOG_TAG, "download sfile=" + fileName);

                File localFile = new File(downloadFilePath + "/" + fileNameUTF8);

                OutputStream outputStream = new FileOutputStream(localFile);

                //boolean success = ftpClient.retrieveFile(new String(sfile.getName().getBytes("GB2312"),"UTF-8"), outputStream);
                boolean success = ftpClient.retrieveFile(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"), outputStream);
                Log.d(LOG_TAG, "download ok? = " + success);

                if (!success)
                    Log.d(LOG_TAG, "download error code = " + ftpClient.getReplyCode() + " reply" + ftpClient.getReply());

                outputStream.flush();
                outputStream.close();

                downloadedFileSum++;
                currentDownloadSize += sfile.getSize();

                mainHandler.sendEmptyMessage(REFLASH_FILESIZE);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public void downloadAndDelBranchFile() {

        downloadedBranchFileSum = 0;

        for (File lfile : deleteBranchFileList) {
            Log.d(LOG_TAG, "del local branch file=" + lfile.getName());
            if (lfile.exists())
                lfile.delete();
        }

        try {
            ftpClient.changeWorkingDirectory(new String((getCurrentBranch() + "/").getBytes("UTF-8"), "ISO-8859-1"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (FTPFile sfile : downloadBranchFileList) {

            try {
                String fileName = sfile.getName();
                String fileNameUTF8 = new String(fileName.getBytes("UTF-8"), "UTF-8");
                Log.d(LOG_TAG, "download branch sfile=" + fileName);

                File localFile = new File(downloadBranchFilePath + "/" + fileNameUTF8);

                OutputStream outputStream = new FileOutputStream(localFile);

                //boolean success = ftpClient.retrieveFile(new String(sfile.getName().getBytes("GB2312"),"UTF-8"), outputStream);
                boolean success = ftpClient.retrieveFile(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"), outputStream);
                Log.d(LOG_TAG, "download ok? = " + success);

                if (!success)
                    Log.d(LOG_TAG, "download error code = " + ftpClient.getReplyCode() + " reply" + ftpClient.getReply());

                outputStream.flush();
                outputStream.close();

                downloadedBranchFileSum++;
                currentDownloadSize += sfile.getSize();

                mainHandler.sendEmptyMessage(REFLASH_FILESIZE);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

}
